package com.cheng.service.FaceService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheng.mapper.UserMapper;
import com.cheng.pojo.User;
import com.cheng.utli.RedisUtil;
import com.cheng.utli.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class FaceServiceImpl  implements FaceService{
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper usermapper;

    public static final String FACE_TOKEN = "FACE_TOKEN";
    public static final long TIME_OUT =  2592000;
    //人脸最低分数
    public static final int MINSCORE =  70;
    //人脸识别错误编码
    public static final String FACEALEAD ="face already exist";

    private static final Logger logger = LoggerFactory.getLogger(FaceServiceImpl.class);

    public  String getFaceToken(){
        //获取token，先从缓存，没有在去调用接口
        String token = (String) redisUtil.get(FACE_TOKEN);
        if(Utils.isBlank(token)){
            token = authService.getAuth();
            redisUtil.set(FACE_TOKEN,authService.getAuth(),TIME_OUT);
            return token;
        }
        return token;
    }

    @Override
    public String addFace(HashMap<String, String> userInfo) {

        User user =  usermapper.checkUserRegister(userInfo.get("user_id"));
        if(user != null){
            return "hasUser";
        }
        //接受前图片编码
        String url = userInfo.get("faceUrl");
        String user_id = userInfo.get("user_id");
        //获得百度云token
        String accessToken = getFaceToken();
        //调用人脸接口，添加人脸
        JSONObject json = new JSONObject();
        json.put("image",url);
        json.put("image_type","URL");
        json.put("max_face_num",5);
        logger.info("=============人脸调用检测接口开始=============");

        //前台传入的人脸数大于1,提示用户重新上传
        JSONObject faceDetect = JSON.parseObject(authService.faceDetect(json,accessToken));
        JSONObject result = faceDetect.getJSONObject("result");
        if(result == null){
            //没有检测到人脸的处理
            return "noHasFace";
        }
        //得到人脸数量
        String faceNum = result.getString("face_num");
        if(!faceNum.equals("1")){
            //检测到人脸数量大于1
            return "max_face_num";
        }

        json.remove("max_face_num");
        logger.info("=============人脸调用注册接口开始=============");

        //获得返回接口的信息
        json.put("group_id", "group_repeat");
        json.put("user_id", user_id);
        json.put("liveness_control", "LOW");
        json.put("quality_control", "LOW");
        JSONObject addFace = JSON.parseObject(authService.addFace(json,accessToken));

        if(addFace.getJSONObject("result")==null){
            if(addFace.getString("error_msg").equals(FACEALEAD)){
                return FACEALEAD;
            }
        }

        JSONObject addFaceJSONObject = addFace.getJSONObject("result");
        //得到注册的人脸 face_token
        String userFaceToken = addFaceJSONObject.getString("face_token");



        logger.info("得到的人脸token为："+userFaceToken);
        //数据库添加操作
        userInfo.put("FACETOKEN",userFaceToken);
        logger.info("================数据库插入操作=================");
        usermapper.addStudent(userInfo);
        return "suc";
    }

    @Override
    public JSONObject searchFace(HashMap<String, String> userInfo) {
        User user =  usermapper.checkUserRegister(userInfo.get("user_id"));

        //接受前图片编码
        String faceToken = userInfo.get("faceToken");
        String user_id = userInfo.get("user_id");
        //获得百度云token
        String accessToken = getFaceToken();
        //调用人脸接口，添加人脸
        JSONObject json = new JSONObject();

        json.put("image",faceToken);
        json.put("image_type","FACE_TOKEN");
        json.put("group_id_list","group_repeat");
        json.put("quality_control","LOW");

        JSONObject searchFace = JSON.parseObject(authService.addFace(json,accessToken));

        return searchFace;
    }

    @Override
    public JSONObject matchFace(HashMap<String, String> userInfo) {
        JSONObject returnJson = new JSONObject();
        User user =  usermapper.getUser(userInfo.get("openId"));

        //得到用户存储的token
        JSONArray match = new JSONArray();
        //用户存储的信息
        JSONObject user1 = new JSONObject();

        user1.put("image",user.getFace_token());
        user1.put("image_type","FACE_TOKEN");
        user1.put("face_type","LIVE");
        user1.put("quality_control","LOW");
        user1.put("liveness_control","LOW");

        //用户传入的信息
        JSONObject user2 = new JSONObject();

        user2.put("image",userInfo.get("faceUrl"));
        user2.put("image_type","URL");
        user2.put("face_type","LIVE");
        user2.put("quality_control","LOW");
        user2.put("liveness_control","LOW");

        match.add(user1);
        match.add(user2);
        //获得百度云token
        String accessToken = getFaceToken();

        JSONObject result = JSON.parseObject(authService.faceMatch(match,accessToken));

        if(result.getString("error_msg").equals("pic not has face")){
            returnJson.put("suc","noFace");
            return returnJson;
        }
        logger.error("result"+result);

        Double score = result.getJSONObject("result").getDouble("score");
        if(score<=MINSCORE){
            returnJson.put("suc","noMatch");
            String faceToken = result.getJSONArray("face_list").getJSONObject(1).getString("face_token");
            returnJson.put("faceToken",faceToken);
            return returnJson;
        }else{
            returnJson.put("suc","noMatch");
            return returnJson;
        }
    }

    @Override
    public JSONObject updateFace(HashMap<String, String> userInfo) {
        //接受前图片编码
        String faceToken = userInfo.get("faceToken");
        String user_id = userInfo.get("user_id");
        //获得百度云token
        String accessToken = getFaceToken();
        //调用人脸接口，修改人脸
        JSONObject json = new JSONObject();

        json.put("image",faceToken);
        json.put("image_type","FACE_TOKEN");
        json.put("group_id_list","group_repeat");
        json.put("user_id",user_id);
        json.put("quality_control","LOW");

        return  JSON.parseObject(authService.updateMatch(json,accessToken));
    }

}
